package cn.broadsense.web.controller.biz;

import cn.broadsense.biz.bo.DataItemChannelBo;
import cn.broadsense.biz.domain.ItemTag;
import cn.broadsense.biz.domain.ItemTagTemplate;
import cn.broadsense.biz.domain.ItemTagTemplateDetails;
import cn.broadsense.biz.service.ItemTagTemplateDetailsService;
import cn.broadsense.biz.service.ItemTagTemplateService;
import cn.broadsense.biz.vo.ItemTagTemplateVo;
import cn.broadsense.common.annotation.Anonymous;
import cn.broadsense.common.annotation.Log;
import cn.broadsense.common.core.controller.BaseController;
import cn.broadsense.common.core.domain.R;
import cn.broadsense.common.core.domain.entity.SysRole;
import cn.broadsense.common.core.page.TableDataInfoResult;
import cn.broadsense.common.enums.BusinessType;
import cn.broadsense.common.utils.poi.ExcelUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lijian
 * @description
 * @date 2024年09月12日 下午3:33
 */
@RestController
@Api(tags = "标签模板管理")
@RequestMapping("/item/tag/template")
@RequiredArgsConstructor
@Anonymous
public class ItemTagTemplateController extends BaseController {

    private final ItemTagTemplateService itemTagTemplateService;

    private final ItemTagTemplateDetailsService itemTagTemplateDetailsService;

    @Log(title = "标签模板管理-新增", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增模板")
    @PostMapping("/add")
    public R insert(@Validated @RequestBody ItemTagTemplateVo vo) {
        itemTagTemplateService.saveItemTagTemplate(vo);
        return R.ok();
    }

    @Log(title = "标签模板管理-编辑", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "编辑模板")
    @PutMapping("/update/{id}")
    public R update(@Validated @RequestBody ItemTagTemplateVo vo, @PathVariable Long id) {
        ItemTagTemplate one = itemTagTemplateService.getById(id);
        if (one == null) {
            return R.fail("模板不存在");
        }
        one.setTemplateName(vo.getTemplateName());
        one.setTemplateSpecification(vo.getTemplateSpecification());
        one.setDetailVoList(vo.getDetailVoList());
        itemTagTemplateService.updateItemTagTemplate(one);
        return R.ok();
    }

    @ApiOperation(value = "启用/取消启用")
    @PutMapping("/changeStatus/{id}/{status}")
    public R changeStatus(@PathVariable Long id, @PathVariable Integer status) {
        ItemTagTemplate one = itemTagTemplateService.getById(id);
        if (one == null) {
            return R.fail("模板不存在");
        }
        one.setStatus(status);
        itemTagTemplateService.updateById(one);
        return R.ok();
    }

    @Log(title = "标签模板管理-删除", businessType = BusinessType.DELETE)
    @ApiOperation("删除标签模板")
    @DeleteMapping("/{ids}")
    public R deleteTagType(@PathVariable Integer[] ids) {
        return R.ok(itemTagTemplateService.removeByIds(Arrays.asList(ids)));
    }

    @ApiOperation("列表")
    @GetMapping("/list")
    public TableDataInfoResult<List<ItemTagTemplate>> list(@ApiParam(value = "模板名称") @RequestParam(required = false) String templateName,
                                                              @ApiParam(value = "模板状态 1：启用 0：未启用") @RequestParam(required = false) Integer status,
                                                              @RequestParam(required = false) @ApiParam(value = "开始时间 YYYY-MM-DD") String startTime,
                                                              @RequestParam(required = false) @ApiParam(value = "结束时间 YYYY-MM-DD") String endTime) {
        startPage();
        List<ItemTagTemplate> templates = itemTagTemplateService.lambdaQuery()
                .like(StrUtil.isNotBlank(templateName), ItemTagTemplate::getTemplateName, templateName)
                .eq(Objects.nonNull(status), ItemTagTemplate::getStatus, status)
                .between(StrUtil.isNotBlank(startTime) && StrUtil.isNotEmpty(endTime), ItemTagTemplate::getUpdateTime, startTime, endTime)
                .list();
        List<ItemTagTemplateVo.ItemTagTemplateDetailVo> list = itemTagTemplateDetailsService.getList();
        templates.forEach(x -> {
            List<ItemTagTemplateVo.ItemTagTemplateDetailVo> collect = list.stream().filter(y -> y.getItemTagTemplateId().equals(x.getId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {
                String tagNames = collect.stream().map(ItemTagTemplateVo.ItemTagTemplateDetailVo::getFieldName).collect(Collectors.joining("、"));
                x.setTagNames(tagNames);
                x.setDetailVoList(collect);
            }
        });
        return getDataTableResult(templates);
    }

    @ApiOperation("详情")
    @GetMapping("/detail/{id}")
    public R<ItemTagTemplate> detail(@PathVariable Long id) {
        ItemTagTemplate one = itemTagTemplateService.getById(id);
        if (one == null) {
            return R.fail("模板不存在");
        }
        return R.ok(one);
    }

    @ApiOperation("导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @ApiParam(value = "模板名称") @RequestParam(required = false) String templateName,
                       @ApiParam(value = "模板状态 1：启用 0：未启用") @RequestParam(required = false) Integer status,
                       @RequestParam(required = false) @ApiParam(value = "开始时间 YYYY-MM-DD") String startTime,
                       @RequestParam(required = false) @ApiParam(value = "结束时间 YYYY-MM-DD") String endTime,
                       @RequestParam(required = false) @ApiParam(value = "选中ID") Long[] ids) {
        List<ItemTagTemplate> templates = itemTagTemplateService.lambdaQuery()
                .like(StrUtil.isNotBlank(templateName), ItemTagTemplate::getTemplateName, templateName)
                .eq(Objects.nonNull(status), ItemTagTemplate::getStatus, status)
                .between(StrUtil.isNotBlank(startTime) && StrUtil.isNotEmpty(endTime), ItemTagTemplate::getUpdateTime, startTime, endTime)
                .in(Objects.nonNull(ids), ItemTagTemplate::getId, ids)
                .list();
        ExcelUtil<ItemTagTemplate> util = new ExcelUtil<>(ItemTagTemplate.class);
        util.exportExcel(response, templates, "模板数据");
    }

    @PostMapping("/import")
    @ApiOperation("导入模板")
    @Log(title = "标签模板管理-导入模板", businessType = BusinessType.IMPORT)
    public R<Void> importData(MultipartFile file) throws Exception {
        ExcelUtil<ItemTagTemplate> util = new ExcelUtil<ItemTagTemplate>(ItemTagTemplate.class);
        List<ItemTagTemplate> list = util.importExcel(file.getInputStream());
        itemTagTemplateService.importItemTagTemplateList(list);
        return R.ok();
    }

    @ApiOperation("导入模板下载")
    @GetMapping("/import/template")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<ItemTagTemplate> util = new ExcelUtil<ItemTagTemplate>(ItemTagTemplate.class);
        util.importTemplateExcel(response, "导入模板数据");
    }

}
